<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="学习,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="简介在angularjs中，子作用域通常会原型继承于其父作用域。有一个例外是当指令使用scope:{…}来定义–这创建了一个没有原型继承的”独立”作用域，这会在创建”可重复使用的组件”的指令时经常使用。如果你设置了scope:true,这个指令会使用原型继承。通常情况下作用域继承非常直白，你甚至不需要知道它在发生什么，直到在一个定义在父作用域上原始类型(例如:number,string,boole">
<meta name="keywords" content="学习">
<meta property="og:type" content="article">
<meta property="og:title" content="angularjs之作用域详解">
<meta property="og:url" content="https://youandme66.github.io/2017/03/11/second/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="简介在angularjs中，子作用域通常会原型继承于其父作用域。有一个例外是当指令使用scope:{…}来定义–这创建了一个没有原型继承的”独立”作用域，这会在创建”可重复使用的组件”的指令时经常使用。如果你设置了scope:true,这个指令会使用原型继承。通常情况下作用域继承非常直白，你甚至不需要知道它在发生什么，直到在一个定义在父作用域上原始类型(例如:number,string,boole">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends1.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends2.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends3.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends4.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends4.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends5.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends6.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends7.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends7.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends7.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends8.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends9.png">
<meta property="og:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends10.png">
<meta property="og:updated_time" content="2017-03-11T06:06:58.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="angularjs之作用域详解">
<meta name="twitter:description" content="简介在angularjs中，子作用域通常会原型继承于其父作用域。有一个例外是当指令使用scope:{…}来定义–这创建了一个没有原型继承的”独立”作用域，这会在创建”可重复使用的组件”的指令时经常使用。如果你设置了scope:true,这个指令会使用原型继承。通常情况下作用域继承非常直白，你甚至不需要知道它在发生什么，直到在一个定义在父作用域上原始类型(例如:number,string,boole">
<meta name="twitter:image" content="https://youandme66.github.io/2017/03/11/second/javascript_extends1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/03/11/second/">





  <title> angularjs之作用域详解 | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/03/11/second/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                angularjs之作用域详解
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-03-11T00:00:00+08:00">
                2017-03-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/angularjs/" itemprop="url" rel="index">
                    <span itemprop="name">angularjs</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/03/11/second/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/03/11/second/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/03/11/second/" class="leancloud_visitors" data-flag-title="angularjs之作用域详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>在angularjs中，子作用域通常会原型继承于其父作用域。有一个例外是当指令使用scope:{…}来定义–这创建了一个没有原型继承的”独立”作用域，这会在创建”可重复使用的组件”的指令时经常使用。如果你设置了scope:true,这个指令会使用原型继承。<br>通常情况下作用域继承非常直白，你甚至不需要知道它在发生什么，直到在一个定义在父作用域上原始类型(例如:number,string,boolean)在子作用域中使用了双向数据绑定(即表单元素，ng-model)。这并不会像大多数人期望的那样工作，而是子作用域得到了它自己的属性，从而覆盖了父作用域上的同名属性。这不是angularjs做的事情-这是JavaScript的原型继承其作用了。新入门的angularjs开发者通常情况下不会意识到ng-repeat、ng-switch、ng-view和ng-include都创建了新的子作用域，所以当使用这些指令的时候，经常会有这种问题发生。<br>关于原始类型的这个问题通过下面的这个最佳建议最容易避免:在你的模型中始终使用’<br>在模型中使用’.’，会确保原型继承始终发生，所以，使用代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type=<span class="string">"text"</span> ng-model=<span class="string">"someObj.prop1"</span>/&gt;</span><br><span class="line">而不是</span><br><span class="line">&lt;input type=<span class="string">"text"</span> ng-model=<span class="string">"prop1"</span>/&gt;</span><br></pre></td></tr></table></figure>
<p>如果你必须要使用原始类型，有以下两种解决方法:<br>1、在子作用域使用$parent.parentScopeProperty.这会阻止子作用域创建自己的属性。<br>2、在父作用域上定义一个函数，在子作用域上调用，通过该函数传递父作用域上的原始值。</p>
<h3 id="JavaScript原型继承"><a href="#JavaScript原型继承" class="headerlink" title="JavaScript原型继承"></a>JavaScript原型继承</h3><p>首先我们应该对JavaScript原型继承有一个深入的了解很有必要，尤其你具有服务器端开发的背景，并且对于传统的继承很熟悉。让我们先来复习一下。<br>假设parentScope具有如下属性,aString,aNumber,anArray,anObject和一个aFunction.如果childScope原型继承于parentScope,如下:<br><img src="/2017/03/11/second/javascript_extends1.png" alt="图片加载中..."><br>(注意:为了节省空间，我把anArray展示成一个蓝色的三个值的对象，而不是一个蓝色的拥有三个分离的灰色的对象)<br>如果我们在childScope上获取parentScope上定义的对象，JavaScript会首先在childscope上查找，没有找到该属性，查找其继承的scope,找到这个属性(如果在parentScope上没有找到该属性，会继续查找原型链…直到到达rootScope)。所以，以下全都为真。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">childScope.aString === <span class="string">'parent string'</span></span><br><span class="line">childScope.anArray[<span class="number">1</span>] === <span class="number">20</span></span><br><span class="line">childScope.anObject.property1 === <span class="string">'parent prop1'</span></span><br><span class="line">childScope.aFunction() === <span class="string">'parent output'</span></span><br></pre></td></tr></table></figure>
<p>假设我们有如下代码:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">childScope.aString = <span class="string">'child string'</span></span><br></pre></td></tr></table></figure></p>
<p>原型链并没有被遍历，一个新的属性会被添加到childScope上。同时，这个新属性隐藏了和parentScope具有同样名称的属性。这对我们下面讨论ng-repeat和ng-include非常重要<br><img src="/2017/03/11/second/javascript_extends2.png" alt="图片加载中..."><br>假设我们又做了如下操作</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">childScope.anArray[<span class="number">1</span>]=<span class="number">22</span></span><br><span class="line">childScope.anObject.property1 = <span class="string">'child prop1'</span></span><br></pre></td></tr></table></figure>
<p>原型链被访问了，因为对象(anArray和anObject)在childScope中没有被找到。这两个对象在parentScope中被找到，属性的值在原对象上别更新了。childScope上不会增加新的属性，没有新的对象创建(在JavaScript中数组和函数同样是对象)。<br><img src="/2017/03/11/second/javascript_extends3.png" alt="图片加载中..."><br>假设我们做如下操作:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">childScope.anArray = [<span class="number">100</span>,<span class="number">555</span>]</span><br><span class="line">childScope.anObject = [name:<span class="string">'Mark'</span>,<span class="attr">country</span>:<span class="string">'USA'</span>]</span><br></pre></td></tr></table></figure>
<p>原型链不会被访问，childScope会创建两个新的对象属性，隐藏了和parentScope具有相同名称的属性。<br><img src="/2017/03/11/second/javascript_extends4.png" alt="图片加载中..."><br>重要结论:<br>1、如果我们读取childScope的某个属性childScope.propertyX,并且childScope具有属性propertyX,那么原型链不会被访问。<br>2、如果我们设置childScope的某个属性propertyX,那么原型链不会被访问。<br>最后一个场景:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">delete</span> childScope.anArray</span><br><span class="line">childScope.anArray[<span class="number">1</span>] === <span class="number">22</span> <span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p>首先我们删除了childScope的属性anArray,然后我们尝试再次去获得该属性，原型链被访问了。<br><img src="/2017/03/11/second/javascript_extends4.png" alt="图片加载中..."><br>这个jsfiddle中你可看到javascript原型继承的例子和结果(打开你的浏览器的控制台查看输出)</p>
<h3 id="angular-scope继承"><a href="#angular-scope继承" class="headerlink" title="angular scope继承"></a>angular scope继承</h3><p>1、如下的指令创建了新的scope，并且基于原型继承:ng-repeat,ng-include,ng-switch,ng-controller,使用scope:true的指令，使用transclude:true指令。<br>2、如下的指令创建了新的scope,并且没有基于原型继承:使用scope:{…}的指令，这创建了”孤立”的scope.</p>
<p>ng-include<br>假设我们的controller中的代码如下:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$scope.myPrimitive = <span class="number">50</span>;</span><br><span class="line">$scope.myObject = &#123;<span class="attr">aNumber</span>:<span class="number">11</span>&#125;;</span><br></pre></td></tr></table></figure>
<p>html如下:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/ng-template"</span> <span class="attr">id</span>=<span class="string">"/tpl1.html"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">ng-model</span>=<span class="string">"myPrimitive"</span>&gt;</span></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-include</span> <span class="attr">src</span>=<span class="string">"'/tpl1.html'"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/ng-template"</span> <span class="attr">id</span>=<span class="string">"/tpl2.html"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">ng-model</span>=<span class="string">"myObject.aNumber"</span>&gt;</span></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-include</span> <span class="attr">src</span>=<span class="string">"'/tpl2.html'"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>每一个ng-include生成了一个新的基于其父作用域原型继承的子作用域。<br><img src="/2017/03/11/second/javascript_extends5.png" alt="图片加载中..."><br>修改第一个textbox中的值’77’会导致子作用域创建一个新的myPrimitive属性，并且隐藏了父作用域的同名属性，这可能不是你所希望的。<br><img src="/2017/03/11/second/javascript_extends6.png" alt="图片加载中..."><br>修改第二个textbox的值为’99’不会导致创建一个新的子属性。因为tpl2.html绑定了一个对象的属性当ngModel查找对象myObject时原型继承起作用了，最终在parentScope中找到了该属性。<br><img src="/2017/03/11/second/javascript_extends7.png" alt="图片加载中..."><br>如果不想将model从原始类型改为对象类型的话，我们可以使用$parent来重写一个模板。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">ng-model</span>=<span class="string">"$parent.myprimitive"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>这次修改第一个textbox的值不会导致生成一个新的子属性。模型现在绑定了parentScope中的属性(因为$parent是子作用域指向父作用域的一个引用)。<br><img src="/2017/03/11/second/javascript_extends7.png" alt="图片加载中..."><br>对于所有作用域(不管是否是原型继承)，angular会通过作用域上的属性<br>\$parent指向scope的父作用域<br>\$\$childHeader指向scope的第一个子作用域<br>\$\$childTail指向scope的最后一个子作用域<br>\$\$nextSibling指向scope的下一个相邻作用域<br>\$\$prevSibling指向scope的上一个相邻作用域<br>这些关系用于AngularJS内部历遍，如\$broadcast和\$emit事件广播，\$digest处理等。<br>对于不涉及表单元素的情况，另一个解决方案是在父作用域中定义一个函数来修改原始数据类型。子作用域总是调用这个函数，由于原型继承子作用域能够访问到该函数。例如:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//in the parent scope</span></span><br><span class="line">$scope.setMyPrimitive = <span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">    $scope.myPrimitive = value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是一个使用了”parent function”的简单的jsfiddle</p>
<p>ng-switch<br>ng-switch scope 的继承和ng-include类似。因此如果你需要双向数据绑定到父作用域中的一个原始数据类型上，使用$parent或者将model改为对象的某个属性。这会避免子作用域隐藏了父作用域的属性。</p>
<p>ng-repeat<br>ng-repeat 和以上指令有点差别。假设我们的controller如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$scope.myArrayOfPrimitives = [<span class="number">11</span>,<span class="number">22</span>];</span><br><span class="line">$scope.myArrayOfObjects = [&#123;<span class="attr">num</span>:<span class="number">10</span>&#125;,&#123;<span class="attr">num</span>:<span class="number">202</span>&#125;]</span><br></pre></td></tr></table></figure>
<p>html如下:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span><span class="tag">&lt;<span class="name">li</span> <span class="attr">ng-repeat</span>=<span class="string">"num in myArrayOfPrimitives"</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">input</span> <span class="attr">ng-model</span>=<span class="string">"num"</span>&gt;</span><span class="tag">&lt;/<span class="name">input</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">ul</span>&gt;</span><span class="tag">&lt;<span class="name">li</span> <span class="attr">ng-repeat</span>=<span class="string">"obj in myArrayOfObjects"</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">input</span> <span class="attr">ng-model</span>=<span class="string">"obj.num"</span>&gt;</span><span class="tag">&lt;/<span class="name">input</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>对于每次 item的iteration，ng-repeate创建了一个从父作用域原型继承的新的作用域，但是它也将item的值分配给新的子作用域上的一个新的属性（新的属性的名称是循环变量的名称）。如下是ng-repeate的源代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">childScope = scope.$<span class="keyword">new</span>(); <span class="comment">// child scope prototypically inherits from parent scope ...     </span></span><br><span class="line">childScope[valueIdent] = value; <span class="comment">// creates a new childScope property</span></span><br></pre></td></tr></table></figure>
<p>如果item是一个原始类型（例如上面的myArrayOfPrimitives），本质上该值的一个拷贝被分配给新的子scope。改变了子scope的属性值（即使用ng-model、也就是子scope属性num）并没有改变父scope引用的数组。所以，在上面第一个ng-repeate，每一个子scope会得到一个独立于myArrayOfPrimitives 的num属性。<br><img src="/2017/03/11/second/javascript_extends7.png" alt="图片加载中..."><br>因此这个ng-repeat不会像你希望的那样工作。在Angular1.0.2（包含）以前，修改textbox的值会改变上图中灰色框的值，并且只在child scope中可见。在Angular 1.0.3以上，修改textbox的值不会有任何影响（参考Artem在Stack Overflow的解释）（此处说法有点不太准确，在较新的Angular版本中，修改textbox的值会改变图中灰色框中的值－－译者注）。我们所希望的是修改input的值能够改变数组myArrayOfPrimitives，而不是子scope的一个原始类型的属性。为了达到这个目的，我们需要将模型改为对象的数组（见第2个例子）。<br>因此，如果item是一个对象，原始对象的引用（非拷贝）会被分配成为新的子scope上的属性。修改子scope的属性值（例如，使用ng-model，obj.num）会修改父scope上的值。在上面的第二个ng-repeat中，我们有如下结论：<br><img src="/2017/03/11/second/javascript_extends8.png" alt="图片加载中..."><br>（注意图中的灰线，能清楚的看到发生了什么）</p>
<p>按照预期工作了。修改textbox的值改变了灰色框中的值，同时对子作用域和父作用域都可见。<br>ng-view<br>和ng-include类似<br>ng-controller<br>和ng-include、ng-switch的原理一致，使用ng-controller的嵌套的控制器会引起正常的原型继承。然而，“不建议在两个控制器中通过$scope的继承关系来共享信息“<br>在控制器中共享数据应该使用服务。</p>
<p>指令<br>1、默认（scope:false）－指令没有创建任何新的作用域，因此不存在任何的原型继承。这很简单，但是同样存在隐患，例如：一个指令可能以为它在作用域上创建了一个新的属性，但实际上它修改了一个现有的属性的值。这对于书写可重复使用的组件来说并不是一个好的选择。<br>2、scope: true－指令创建了一个从父作用域基于原型继承的子作用域。如果在同一个DOM上有多个指令需要创建新的作用域，那么只有一个新的子作用域会被创建。既然有“正常“的原型继承，和ng-include 、ng-switch类似，警惕在父作用域上的原始数据类型的双向数据绑定，子作用域会覆盖掉父作用域上的属性。<br>3、scope: { … }－指令创建了一个新的独立作用域。并且没有原型继承。当你创建可以复用的组件时这是一个好的选择，因为指令不能够直接读取或修改父作用域。然而，通常这种指令需要读取父作用域的某些属性。该对象可以在父作用域和独立作用域上使用“＝“创建双向数据绑定，使用“@“创建单向绑定（父作用域改变会影响子作用域，子作用域改变并不会影响父作用域－－译者注）。也可以使用“&amp;“绑定父作用域上的表达式。所以，这些方法同样给子作用域创建了从父作用域衍生的属性。注意这些属性被用来帮助设置绑定－－在对象中你不能直接引用父作用域的属性名称，你需要使用一个HTML属性。例如：如下，你想要在独立作用域上绑定父作用域的属性parentProp将不会起作用：代码<div my-directive=""> 和scope: { localProp: ‘@parentProp’ }。指令想要绑定的父属性必须要有明确的HTML属性名：代码<div my-directive="" the-parent-prop="parentProp">和scope: { localProp: ‘@theParentProp’ }。独立作用域的proto 引用了一个Scope对象。独立作用域的$parent引用了父作用域，尽管这是一个没有原型继承的独立作用域，但他还是一个子作用域。<br>如下图片中：我们有代码</div></div></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;my-directive interpolated=<span class="string">"&#123;&#123;parentProp1&#125;&#125;"</span> twoway－binding=<span class="string">"parentProp2"</span>&gt; 和 </span><br><span class="line">scope: &#123; <span class="attr">interpolatedProp</span>: <span class="string">'@interpolated'</span>, <span class="attr">twowayBindingProp</span>: <span class="string">'=twowayBinding'</span> &#125;。同样假设在指令的link函数中有代码scope.someIsolateProp = <span class="string">"I'm isolated"</span></span><br></pre></td></tr></table></figure>
<p><img src="/2017/03/11/second/javascript_extends9.png" alt="图片加载中..."><br>最后注意：使用link函数中attrs.$observe(‘attr_name’, function(value) { … })来得到独立作用域中使用‘@‘绑定的属性的值。例如：在link函数中有代码–attrs.$observe(‘interpolated’, function(value) { … }) – value会被设置为11。（scope.interpolatedProp在link函数中没有定义（该文章写的时间较早，译者通过测试Angular1.4.7发现在该版本中，这个属性已经有定义了，值为11）。而scope.twowayBindingProp有定义，因为他使用了‘＝‘ ）。<br>4、transclude: true－指令创建了一个新的 “transcluded” 子作用域，并且原型继承于父作用域。因此，如果你的嵌入的内容（即ng-transclude将被替换的内容）需要双向数据绑定到父作用域上的一个原始类型上，使用$parent，或者将模型改为对象，绑定到改对象的某个属性上。这会避免子作用域覆盖父作用域的属性。<br>内嵌作用域和独立作用域是同胞的－－每个scope的\$parent属性指向同一个父作用域。当内嵌作用域和独立作用域同时存在，独立作用域的\$\$nextSibling 属性会指向内嵌作用域。<br>假设上面的指令增加了属性transclude: true ，scope的示意图如下：<br><img src="/2017/03/11/second/javascript_extends10.png" alt="图片加载中..."><br>这个jsfiddle有一个用来检查独立作用域和他相关的内嵌作用域的showScope()函数。参考该fiddle中的注释中的说明。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>有四种类型的作用域:<br>1、普通原型继承作用域－－ng-include、ng-switch、ng-controller和使用scope: true定义的指令<br>2、含有拷贝属性的普通原型继承作用域－－ng-repeat。每次迭代ng-repeat都会创建一个新的子作用域，同时新的子作用域会得到一个新的属性。<br>3、 独立作用域－－使用scope: {…}定义的指令。这次没有原型继承，但是 ‘=’, ‘@’, and ‘&amp;’提供了一种通过HTML属性获取父作用域属性的机制。<br>4、内嵌作用域－－使用transclude: true定义的指令。这次依旧是正常的基于原型的继承，但是同时他也是任意独立作用域的兄弟作用域。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/11/first/" rel="next" title="正则表达式">
                <i class="fa fa-chevron-left"></i> 正则表达式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/12/third/" rel="prev" title="express之mongoose操作">
                express之mongoose操作 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JavaScript原型继承"><span class="nav-number">2.</span> <span class="nav-text">JavaScript原型继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#angular-scope继承"><span class="nav-number">3.</span> <span class="nav-text">angular scope继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/03/11/second/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
